<template>
  <div class="image-uploader">
    <!-- 上传按钮 -->
    <button 
      @click="openFileDialog" 
      class="upload-btn"
      :disabled="uploading"
      :title="uploading ? '上传中...' : '上传图片'"
    >
      {{ uploading ? '⏳' : '📷' }}
      {{ uploading ? '上传中...' : '添加图片' }}
    </button>

    <!-- 隐藏的文件选择器 -->
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      @change="handleFileSelect"
      style="display: none"
      multiple
    />

    <!-- 上传进度 -->
    <div v-if="uploading" class="upload-progress">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: progress + '%' }"></div>
      </div>
      <span class="progress-text">{{ progress }}%</span>
    </div>

    <!-- 拖拽区域遮罩 -->
    <div
      v-if="dragOver"
      class="drag-overlay"
      @drop="handleDrop"
      @dragover.prevent
      @dragleave="dragOver = false"
    >
      <div class="drag-content">
        <div class="drag-icon">📷</div>
        <div class="drag-text">松开以上传图片</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { fileApi } from '../services/api'
import { toast } from '../utils/message'

interface Props {
  // 最大文件大小（MB）
  maxSize?: number
  // 是否支持多选
  multiple?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  maxSize: 5,
  multiple: false
})

const emit = defineEmits<{
  // 上传成功事件，返回Markdown语法
  success: [markdown: string]
  // 上传失败事件
  error: [error: string]
}>()

const fileInput = ref<HTMLInputElement>()
const uploading = ref(false)
const progress = ref(0)
const dragOver = ref(false)

// 支持的图片类型
const supportedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']

// 打开文件选择对话框
const openFileDialog = () => {
  if (uploading.value) return
  fileInput.value?.click()
}

// 处理文件选择
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files
  if (files && files.length > 0) {
    handleFiles(Array.from(files))
  }
  // 清空input值，允许选择同一个文件
  target.value = ''
}

// 处理拖拽放置
const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  dragOver.value = false
  
  const files = event.dataTransfer?.files
  if (files && files.length > 0) {
    handleFiles(Array.from(files))
  }
}

// 处理文件列表
const handleFiles = async (files: File[]) => {
  if (uploading.value) return

  // 过滤出图片文件
  const imageFiles = files.filter(file => {
    if (!supportedTypes.includes(file.type)) {
      toast.warning(`不支持的文件类型: ${file.name}`)
      return false
    }
    
    if (file.size > props.maxSize * 1024 * 1024) {
      toast.warning(`文件过大: ${file.name} (最大${props.maxSize}MB)`)
      return false
    }
    
    return true
  })

  if (imageFiles.length === 0) {
    return
  }

  // 如果不支持多选，只取第一个文件
  const filesToUpload = props.multiple ? imageFiles : imageFiles.slice(0, 1)
  
  await uploadFiles(filesToUpload)
}

// 上传文件
const uploadFiles = async (files: File[]) => {
  uploading.value = true
  progress.value = 0
  
  const results: string[] = []
  
  try {
    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      
      // 更新进度
      const baseProgress = (i / files.length) * 100
      progress.value = baseProgress
      
      try {
        const response = await fileApi.uploadImage(file)
        
        // 生成Markdown语法
        const fileName = response.fileName || file.name
        const imageUrl = response.fileUrl
        const markdown = `![${fileName}](${imageUrl})`
        
        results.push(markdown)
        
        // 更新进度
        progress.value = ((i + 1) / files.length) * 100
        
        toast.success(`图片上传成功: ${fileName}`)
        
      } catch (error: any) {
        console.error(`上传失败: ${file.name}`, error)
        const errorMessage = error.response?.data?.message || error.message || '上传失败'
        toast.error(`${file.name} 上传失败: ${errorMessage}`)
        emit('error', errorMessage)
      }
    }
    
    if (results.length > 0) {
      // 发送成功事件，将所有Markdown语法合并
      const markdown = results.join('\n\n')
      emit('success', markdown)
    }
    
  } finally {
    uploading.value = false
    progress.value = 0
  }
}

// 处理全局拖拽事件
const handleGlobalDragOver = (event: DragEvent) => {
  event.preventDefault()
  // 检查是否包含文件
  if (event.dataTransfer?.types.includes('Files')) {
    dragOver.value = true
  }
}

const handleGlobalDragLeave = (event: DragEvent) => {
  // 只有当离开整个窗口时才隐藏遮罩
  if (!event.relatedTarget) {
    dragOver.value = false
  }
}

// 绑定全局拖拽事件
document.addEventListener('dragover', handleGlobalDragOver)
document.addEventListener('dragleave', handleGlobalDragLeave)

// 组件卸载时清理事件监听
import { onUnmounted } from 'vue'
onUnmounted(() => {
  document.removeEventListener('dragover', handleGlobalDragOver)
  document.removeEventListener('dragleave', handleGlobalDragLeave)
})
</script>

<style scoped>
.image-uploader {
  position: relative;
}

.upload-btn {
  padding: 0.5rem 1rem;
  background: #42b883;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.upload-btn:hover:not(:disabled) {
  background: #369870;
}

.upload-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.upload-progress {
  margin-top: 0.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #42b883;
  border-radius: 3px;
  transition: width 0.3s;
}

.progress-text {
  font-size: 0.8rem;
  color: #666;
}

.drag-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(66, 184, 131, 0.1);
  backdrop-filter: blur(2px);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.drag-content {
  background: white;
  border: 2px dashed #42b883;
  border-radius: 12px;
  padding: 3rem 4rem;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.drag-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.drag-text {
  font-size: 1.2rem;
  color: #42b883;
  font-weight: 600;
}

/* 深色主题支持 */
.dark .progress-bar {
  background: #3d3d3d;
}

.dark .progress-text {
  color: #b3b3b3;
}

.dark .drag-content {
  background: #2d2d2d;
  color: #e6e6e6;
}
</style>